package main

import (
	"fmt"
	"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"log"
	pb "myrpc/stringlength/stringlength"
	"time"
)

const (
	address = "localhost:50051"
)

func ctxWithToken(ctx context.Context, scheme string, token string) context.Context {
	md := metadata.Pairs("authorization", fmt.Sprintf("%s %v", scheme, token))
	nCtx := metautils.NiceMD(md).ToOutgoing(ctx)
	return nCtx
}

func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("failed to dial %s. %v", address, err)
	}
	client := pb.NewStringLengthServiceClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	ctx = ctxWithToken(ctx, "bearer", "some token")
	ret, err := client.StringLength(ctx, &pb.StringSource{Source: "it's a nice day!"})
	if err != nil {
		log.Fatalf("failed to invoke StringLength. %v", err)
	}
	log.Printf("Reply : %d", ret.Length)
}
